from fastapi import APIRouter, Depends
from backend.library.response import success, fail
from backend.model.user import LoginInfo, UserModel
from backend.library.database import get_db
from backend.library.utils import md5
import time
import uuid

router = APIRouter(prefix="/api/common")

@router.post('/login')
def login( login: LoginInfo, db=Depends(get_db)):
    #用户登录函数
    #如果登陆成功返回用户信息，否则返回None

    # step1 通过username查询用户
    user = UserModel.get_user_by_username(db, login.username)
    if user is None:
        return fail("用户不存在")

    # step2 判断用户状态
    if user.status==0:
        # status==0 账户被锁定
        return fail("用户账号被锁定，请联系管理员")
    if user.login_failure>=4:
        # login_failure>=4 看是否在锁定时间范围内
        now = int(time.time())
        if user.prevent_time > now:
            return fail("用户密码输入错误次数过多，账号被锁定，请稍后重试")

    # step3 判断密码是否正确
    if md5(login.password) == user.password:
        # 如果正确返回Token（归零密码错误次数）
        token = str(uuid.uuid4())
        UserModel.update_user(db, user.id, {"token":token, "login_failure":0})
        return success("登陆成功", {"user_id": user.id, "username":user.realname, "role":user.role, "token":token})
    else:
        # 否则密码错误次数+1
        UserModel.update_user(db, user.id, {"login_failure":user.login_failure+1})
        # 如果密码次数>=4，设置prevent_time
        if user.login_failure+1>=4:
            p = int(time.time()) + 3600   
            UserModel.update_user(db, user.id, {"prevent_time":p})
        return fail("密码错误")

    # md5('123123') -> 4297f44b13955235245b2497399d7a93
    # md5('123123' + 'abcd') -> ???


@router.get("/logout")
def logout():

    return

@router.get("/classList")
def classList():
    classList = [
        '2022级人工智能',
        '2023级人工智能'
    ]
    return success("OK", classList)


@router.get("/teacherList")
def teacherList(db=Depends(get_db)):
    
    total, rows = UserModel.search_user(db, '', 2, 1, 100)
    result = []
    
    return success("OK", [{"id":v.id,"realname":v.realname} for v in rows])


